#!/usr/bin/env ruby

# == Synopsis
# The parser parses the XML files provided by the BlueObelisk Project and
# generates objects of the type ChemicalElement 
# == Copyright
# Copyright (c) 2008 Carsten Niehaus <cniehaus at kde dot org>
# Licence GPLv3

require "rexml/document"
require "chemicalclasses"

# This class parses the file 'elements.xml' and creates one ChemicalElement object per element.
# Each ChemicalElement is then filled with data
class ChemicalParser
	def initialize
		@file = File.new( "elements.xml" )
		@doc = REXML::Document.new @file

		@elements = Array.new
	end

	# Converts the XML-string to the common unit. For example, 'siUnits:kelvin' is converted to 'K'
	def unit2unit( bounit )
		unit = bounit.to_s

		if unit == "units:ev"
			"eV"
		elsif unit == "siUnits:kelvin"
			"K"
		elsif unit == "unit:atmass"
			"u"
		elsif unit == "unit:ang"
			"Angstrom"
		else
			"noUnit"
		end
	end

	# Setting the elementnumber to +number+. I am extra cautions and convert number to integer first.
	def element( number )
		@elements[number.to_i-1]
	end

	# Read in all elements.
	def read
		@doc.elements.each("list/atom") { |element| 
			e = ChemicalElement.new

			element.elements.each("scalar" ) { |scalar|
				ref = scalar.attributes[ "dictRef" ]
				units = scalar.attributes[ "units" ]
				convertedUnit = unit2unit( units )
				
				#puts "The unit is " + units.to_s 
				#puts " and converted:             "+convertedUnit

				if ref == "bo:mass"
					e.mass = ChemicalValue.new(scalar.text, convertedUnit )
				elsif ref == "bo:radiusVDW"
					e.radiusVDW = ChemicalValue.new(scalar.text, convertedUnit )
				elsif ref == "bo:radiusCovalent"
					e.radiusCovalent = ChemicalValue.new(scalar.text, convertedUnit )
				elsif ref == "bo:atomicNumber"
					e.number = ChemicalValue.new(scalar.text, convertedUnit )
				elsif ref == "bo:boilingpoint"
					e.boilingpoint = ChemicalValue.new(scalar.text, convertedUnit )
				elsif ref == "bo:meltingpoint"
					e.meltingpoint = ChemicalValue.new(scalar.text, convertedUnit )
				elsif ref == "bo:ionization"
					e.ionization = ChemicalValue.new(scalar.text, convertedUnit )
				elsif ref == "bo:electronicConfiguration"
					e.electronicConfiguration = ChemicalValue.new(scalar.text, convertedUnit )
				elsif ref == "bo:electronAffinity"
					e.electronAffinity = ChemicalValue.new(scalar.text, convertedUnit )
				elsif ref == "bo:exactMass"
					e.exactMass = ChemicalValue.new(scalar.text, convertedUnit )
				elsif ref == "bo:electronegativityPauling"
					e.electronegativityPauling = ChemicalValue.new(scalar.text, convertedUnit )
				end
			}
			element.elements.each("label" ) { |label|
				ref = label.attributes[ "dictRef" ]

				if ref == "bo:name"
					e.name = ChemicalValue.new( label.attributes[ "value" ], unit2unit("") )
				elsif ref == "bo:symbol"
					e.symbol = ChemicalValue.new( label.attributes[ "value" ], unit2unit("") )
				end
			}

			@elements << e
		}
	end
end


